<template>
  <div>
    <!-- 面包屑导航-->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片MOde 需要一个DIV容器-->
    <el-card>
      <!-- 搜索区-->
      <el-row :gutter="5">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            clearable
            @clear="getUserList"
            v-model="queryInfo.query"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="3"
          ><el-button type="primary" @click="dialogVisible"
            >添加用户</el-button
          ></el-col
        >
      </el-row>
      <!-- 列表区 -->
      <el-table :data="UserList" border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
          width="180"
        ></el-table-column>
        <el-table-column label="登录状态" width="180">
          <!-- template 插槽  scope.row 能拿到表单数据-->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="权限" width="180">
          <template slot-scope="scope">
            <!-- button属性 size 修改按钮尺寸-->
            <el-tooltip content="修改按钮" placement="top" :enterable="false">
              <el-button
                @click="showUserUpdate(scope.row.id)"
                size="mini"
                type="primary"
                icon="el-icon-edit"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除按钮" placement="top" :enterable="false">
              <el-button
                @click="deleteUserBtn(scope.row.id)"
                size="mini"
                type="danger"
                icon="el-icon-delete"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button
                @click="setRolesDialog(scope.row)"
                size="mini"
                type="warning"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialog"
      width="50%"
      @close="addResetTest"
    >
      <!-- 主体区 -->
      <el-form
        :label-position="formFont"
        label-width="80px"
        :model="addUserModel"
        :rules="addUserRules"
        ref="addUserRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserModel.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="addUserModel.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserModel.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserModel.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="updateDialog"
      width="50%"
      @close="updateResetTest"
    >
      <!-- 主体区 -->
      <el-form
        :label-position="formFont"
        label-width="80px"
        :model="updataModel"
        :rules="addUserRules"
        ref="updateUserRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updataModel.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updataModel.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="updataModel.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateTest">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setDialog" width="50%" @close="notInfo">
      <span>当前的用户: {{ userInfo.username }}</span
      ><br />
      <span>当前的角色: {{ userInfo.role_name }}</span
      ><br />
      <span>
        分配的角色:
        <template>
        <el-select placeholder="请选择" v-model="setRolesOption">
          <el-option v-for="name in roleList" :key="name.id" :label="name.roleName" :value="name.id"></el-option>
        </el-select>
        </template>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="notInfo">取 消</el-button>
        <el-button type="primary" @click="savaRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/*eslint-disable*/
export default {
  data() {
    //验证邮箱规则
    // rule 验证规则 value 要验证的值 cb 回调函数
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([A-z0-9]{6,18})(\w|\-)+@[A-z0-9]+\.([A-z]{2,3})$/;

      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法邮箱格式"));
    };
    //验证手机规则
    var checkMobile = (rule, value, cb) => {
      const regMobile =
        /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法手机格式"));
    };

    return {
      // 角色列表
      roleList:[],
      // 分配角色下拉框数据
      setRolesOption:'',
      // 分配角色数据
      userInfo: [],
      //表单字体靠哪边对齐
      formFont: "right",
      queryInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        // 当前显示几条数据
        pagesize: 2,
      },
      UserList: [],
      total: 0,
      // 控制添加用户的对话框的显示和隐藏
      addDialog: false,
      // 控制修改用户的对话框的显示和隐藏
      updateDialog: false,
      // 控制分配角色的对话框的显示和隐藏
      setDialog: false,
      // 对话框表单数据
      addUserModel: {
        username: "123456789",
        password: "123456789",
        email: "1980488019@qq.com",
        mobile: "13550000000",
      },
      updataModel: {},
      // 验证规则
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 6 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: ref } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (ref.meta.status !== 200) {
        return this.$message.console.error("获取用户列表失败");
      }
      this.UserList = ref.data.users;
      this.total = ref.data.total;
    },
    // 监视 pagination @size
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监视 pagination @change  页码值的变化
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 监听 swich 开关状态的改变
    async userStateChange(userinfo) {
      const { data: ref } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      console.log(ref.meta.status);
      if (ref.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("更新用户信息失败");
      }
      this.$message.success("更新用户信息成功");
      //         const { data: res } = await this.$http.put(`/users/${userinfo.id}/state/${userinfo.mg_state}`)
      //   // console.log(res)
      //   if (res.meta.status !== 200) {
      //     // 还原操作
      //     userinfo.mg_state = !userinfo.mg_state
      //    return this.$message.error('更新用户状态失败！')
      //   }
      //   this.$message.success('更新用户状态成功！')
    },
    dialogVisible() {
      this.addDialog = true;
    },
    // 当关闭对话框时的事件
    addResetTest() {
      this.$refs.addUserRef.resetFields();
    },
    updateResetTest() {
      this.$refs.updateUserRef.resetFields();
    },
    // 点击对话窗确定按钮事件  validate 验证
    addUser() {
      this.$refs.addUserRef.validate(async (valid) => {
        //  console.log(valid); // 返回True
        if (!valid) return;
        const { data: ref } = await this.$http.post(
          "/users",
          this.addUserModel
        );
        if (ref.meta.status !== 201) {
          return this.$message.error("添加用户失败");
        }
        this.addDialog = false;
        this.$message.success("添加用户成功");
        // 修改成功后重新获取用户列表
        this.getUserList();
      });
    },
    // 展示编辑用户对话框
    async showUserUpdate(id) {
      // console.log(id);
      const { data: ref } = await this.$http.get("/users/" + id);
      if (ref.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      this.updataModel = ref.data;
      this.updateDialog = true;
    },
    // 修改用户信息预验证
    updateTest() {
      this.$refs.updateUserRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        //   // 验证通过则提交
        const { data: ref } = await this.$http.put(
          "/users/" + this.updataModel.id,
          {
            email: this.updataModel.email,
            mobile: this.updataModel.mobile,
          }
        );
        this.$message.success("修改成功");
        this.updateDialog = false;
      });
    },
    async deleteUserBtn(id) {
      const deletebtn = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => {
        return err;
      });
      // 按取消返回字符串 cancel
      // 按确定返回字符串 confirm

      if (deletebtn === "cancel") {
        return this.$message.info("取消删除");
      }
      const { data: ref } = await this.$http.delete("/users/" + id);
      if (ref.meta.status !== 200) {
        return this.$message.error("未知错误，删除用户失败");
      } else {
        this.getUserList();
        return this.$message.success("删除用户成功");
      }
    },
    async setRolesDialog(row) {
      // 用户信息
      this.userInfo = row
      // 获取角色列表
      const {data: res} = await this.$http.get('/roles')
      this.roleList=res.data
      this.setDialog = true;
    },
    async savaRolesInfo(){
      if(!this.setRolesOption){
        return this.$message.error('角色未更改')
      }
      const {data: res} = await this.$http.put('/users/'+  this.userInfo.id +'/role', {'rid':this.setRolesOption})
      if(res.meta.status !== 200){
        return this.$message.error("发生未知错误")
      }
      this.getUserList()
      this.setDialog=false
      this.setRolesOption=''
      this.roleList=[]
      this.userInfo=[]
      return this.$message.success('修改角色成功')
    },
    notInfo(){
      this.setDialog=false
      this.setRolesOption=''
      this.roleList=[]
      this.userInfo=[]
    }
  }
}
</script>

<style lang="less" scoped>
span {
  display: flex;
  align-items: center;
}
</style>
